import React, { Component } from 'react'

export default class ComFrom extends Component {
  constructor() {
    super()
    this.state = {
      val1: '',
      val2: '',
      val3: '',
      val4: [],
      val5: ''
    }
    this.inputRef = React.createRef()
  }
  val1Handler(e) {
    this.setState({
      val1: e.target.value
    })
  }
  val2Handler(e) {
    this.setState({
      val2: e.target.value
    })
  }
  val3Handler(e) {
    this.setState({
      val3: e.target.value
    })
  }
  val4Handler(e) {
    let arr = this.state.val4;
    // 判断数组中是否有这个选项，有就剔除没有就加入
    if(arr.includes(e.target.value)) {
      // 数组中已包含
      arr.splice(arr.indexOf(e.target.value), 1)
    }else {
      // 数组中不包含
      arr.push(e.target.value);
    }
    console.log(arr);
    this.setState({
      val4: arr
    })
  }
  val5Handler(e) {
    this.setState({
      val5: e.target.value
    })
  }
  componentDidMount() {
    this.setState({
      val1: 777
    })
  }
  submitHandler(e){
    e.preventDefault();
    console.log(this.inputRef.current.files[0].name);
  }
  render() {
    return (
      <div>
        <p>react对于表单控件的处理：1.受控组件 2.非受控组件</p>
        {/* 受控组件：是指可以通过代码控制的表单控件哎，例如单选多选下拉等... */}
        <input value={this.state.val1} onChange={(e)=>this.val1Handler(e)}></input>
        <p>您输入的值：{this.state.val1}</p>
        <hr></hr>
        <textarea value={this.state.val2} onChange={(e)=>this.val2Handler(e)}></textarea>
        <p>您输入的值：{this.state.val2}</p>
        <hr></hr>
        <div>请选择性别</div>
        <input type="radio" value="1" name="sex" onChange={(e)=>this.val3Handler(e)} />男
        <input type="radio" value="2" name="sex" onChange={(e)=>this.val3Handler(e)} />女
        <p>您输入的值：{this.state.val3}</p>
        <hr></hr>
        <div>请选择工作地</div>
        <input type="checkbox" value="changsha" name="place" onChange={(e)=>this.val4Handler(e)} />长沙
        <input type="checkbox" value="hangzhou" name="place" onChange={(e)=>this.val4Handler(e)} />杭州
        <input type="checkbox" value="nanjing" name="place" onChange={(e)=>this.val4Handler(e)} />南京
        <input type="checkbox" value="shanghai" name="place" onChange={(e)=>this.val4Handler(e)} />上海
        <p>您输入的值：
          {
            this.state.val4.map(item => {
              return <span key={item}>{item},</span>
            })
          }</p>
        <hr></hr>
        <p>选择收货地址</p>
        <select value={this.state.val5} onChange={(e)=>this.val5Handler(e)}>
          <option value="1">京</option>
          <option value="2">津</option>
          <option value="3">沪</option>
          <option value="4">渝</option>
        </select>
        <p>您输入的值：{this.state.val5}</p>
        <hr></hr>
        <hr></hr>
        <form onSubmit={(e)=>this.submitHandler(e)}>
          <span>上传文件</span>
          <input type="file" ref={this.inputRef} />
          <button type="submit">submit</button>
        </form>
      </div>
    )
  }
}
